package cn.iocoder.yudao.module.scrm.controller.admin.refund;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.number.NumberUtils;
import cn.iocoder.yudao.module.scrm.annotations.FieldCompareValidator;
import cn.iocoder.yudao.module.scrm.annotations.FieldCompareValidators;
import cn.iocoder.yudao.module.scrm.controller.admin.receivable.vo.ReceivableRespVO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.customer.CustomerDO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.receivable.ReceivableDO;
import cn.iocoder.yudao.module.scrm.enums.common.CrmBizTypeEnum;
import cn.iocoder.yudao.module.scrm.enums.refund.ScrmRefundCommissionStatusEnum;
import cn.iocoder.yudao.module.scrm.enums.refund.ScrmRefundInvoiceStatusEnum;
import cn.iocoder.yudao.module.scrm.enums.schedules.ScrmSchedulesStatusEnum;
import cn.iocoder.yudao.module.scrm.enums.util.FieldNameType;
import cn.iocoder.yudao.module.scrm.service.customer.CustomerService;
import cn.iocoder.yudao.module.scrm.service.order.OrderService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.permission.PermissionApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Stream;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertListByFlatMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.common.util.collection.MapUtils.findAndThen;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

import cn.iocoder.yudao.module.scrm.controller.admin.refund.vo.*;
import cn.iocoder.yudao.module.scrm.dal.dataobject.refund.RefundDO;
import cn.iocoder.yudao.module.scrm.service.refund.RefundService;

@Tag(name = "管理后台 - 退款")
@RestController
@RequestMapping("/scrm/refund")
@Validated
public class RefundController {

    @Resource
    private RefundService refundService;

    @Resource
    private CustomerService customerService;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private OrderService orderService;

    @Resource
    private DeptApi deptApi;

    @Resource
    private PermissionApi permissionApi;


    @PostMapping("/create")
    @Operation(summary = "创建退款")
    @FieldCompareValidators( foreignKeyType = CrmBizTypeEnum.CRM_REFUND,foreignKeyFieldName = FieldNameType.SCRM_PRICE,fieldCompareValidator = {
            @FieldCompareValidator(majorJeyType = CrmBizTypeEnum.CRM_ORDER,majorJeyFieldName = FieldNameType.SCRM_ORDER_TOTAL_MONEY,message = "金额限制！")
    })
    @PreAuthorize("@ss.hasPermission('scrm:refund:create')")
    public CommonResult<Long> createRefund(@Valid @RequestBody RefundSaveReqVO createReqVO) {
        return success(refundService.createRefund(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新退款")
    @PreAuthorize("@ss.hasPermission('scrm:refund:update')")
    @FieldCompareValidators( foreignKeyType = CrmBizTypeEnum.CRM_REFUND,foreignKeyFieldName = FieldNameType.SCRM_PRICE,fieldCompareValidator = {
            @FieldCompareValidator(majorJeyType = CrmBizTypeEnum.CRM_ORDER,majorJeyFieldName = FieldNameType.SCRM_ORDER_TOTAL_MONEY,message = "金额限制！")
    })
    public CommonResult<Boolean> updateRefund(@Valid @RequestBody RefundSaveReqVO updateReqVO) {
        refundService.updateRefund(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除退款")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('scrm:refund:delete')")
    public CommonResult<Boolean> deleteRefund(@RequestParam("id") Long id) {
        refundService.deleteRefund(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得退款")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('scrm:refund:query')")
    public CommonResult<RefundRespVO> getRefund(@RequestParam("id") Long id) {
        RefundDO refund = refundService.getRefund(id);
        return success(buildRefundDetail(refund));
    }

    @GetMapping("/page")
    @Operation(summary = "获得退款分页")
    @PreAuthorize("@ss.hasPermission('scrm:refund:query')")
    public CommonResult<PageResult<RefundRespVO>> getRefundPage(@Valid RefundPageReqVO pageReqVO) {
        //不是超级管理员默认查询自己的数据-是超级管理员直接查询所有的
        Long loginUserId = getLoginUserId();
        if(CollectionUtils.isAnyEmpty(pageReqVO.getOwnerUserId()) && !permissionApi.roleIsSuperAdmin(loginUserId).getCheckedData()) {
            pageReqVO.setOwnerUserId(Collections.singletonList(Objects.requireNonNull(getLoginUserId()).toString()));
        }
        PageResult<RefundDO> pageResult = refundService.getRefundPage(pageReqVO);
        return success(new PageResult<>(buildRefundDetailList(pageResult.getList()), pageResult.getTotal()));
//        return success(BeanUtils.toBean(pageResult, RefundRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出退款 Excel")
    @PreAuthorize("@ss.hasPermission('scrm:refund:export')")
    @OperateLog(type = EXPORT)
    public void exportRefundExcel(@Valid RefundPageReqVO pageReqVO,
                                  HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<RefundDO> list = refundService.getRefundPage(pageReqVO).getList();
        // 导出 Excel
        List<RefundRespVO> refundRespVOList = buildRefundDetailList(list);
        ExcelUtils.write(response, "退款.xls", "数据", RefundRespVO.class,
                refundRespVOList);
    }

    private RefundRespVO buildRefundDetail(RefundDO refund) {
        if (refund == null) {
            return null;
        }
        return buildRefundDetailList(Collections.singletonList(refund)).get(0);
    }

    private List<RefundRespVO> buildRefundDetailList(List<RefundDO> refundList) {
        if (CollUtil.isEmpty(refundList)) {
            return Collections.emptyList();
        }
        // 1.1 获取客户列表
        Map<Long, CustomerDO> customerMap = customerService.getCustomerMap(
                convertSet(refundList, RefundDO::getCustomerId));
        // 1.2 获取创建人、负责人列表
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMapNotCheckDataPermission(convertListByFlatMap(refundList,
                contact -> Stream.of(NumberUtils.parseLong(contact.getCreator()), convertToLong(contact.getOwnerUserId()))));


        Map<Long, DeptRespDTO> deptMap = deptApi.getDeptMapNotCheckDataPermission(convertSet(userMap.values(), AdminUserRespDTO::getDeptId));

        Map<Integer, OrderDO> orderMap = orderService.getOrderMap(convertSet(refundList, RefundDO::getOrderId));
        // 2. 拼接结果
        return BeanUtils.toBean(refundList, RefundRespVO.class, refundRespVO -> {
            // 2.1 拼接客户名称
            findAndThen(customerMap, refundRespVO.getCustomerId(), customer -> refundRespVO.setCustomerName(customer.getName()));
            // 2.2 拼接负责人、创建人名称
            findAndThen(userMap, refundRespVO.getOwnerUserId(), user -> {
                refundRespVO.setOwnerUserName(user.getNickname());
                findAndThen(deptMap, user.getDeptId(), dept -> refundRespVO.setOwnerUserDeptName(dept.getName()));
            });
            MapUtils.findAndThen(userMap, NumberUtils.parseLong(refundRespVO.getCreator()),
                    user -> {
                        refundRespVO.setCreatorName(user.getNickname());
                        findAndThen(deptMap, user.getDeptId(), dept -> refundRespVO.setCreatorDeptName(dept.getName()));
                    });
            // 2.3 拼接订单号
            MapUtils.findAndThen(orderMap, refundRespVO.getOrderId(), order -> refundRespVO.setOrderTitle(order.getTitle()));

            refundRespVO.setInvoiceShowName(ScrmRefundInvoiceStatusEnum.getDescriptionByCode(refundRespVO.getInvoice()));
            refundRespVO.setCommissionShowName(ScrmRefundCommissionStatusEnum.getDescriptionByCode(refundRespVO.getCommission()));

        });
    }

    // 辅助方法：将 String 转换为 Long
    private Long convertToLong(String id) {
        try {
            return id != null ? Long.valueOf(id) : null;
        } catch (NumberFormatException e) {
            // 处理转换异常，返回 null 或者记录日志
            return null;
        }
    }

}